﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using eOfficeDevManager;
using System.Xml;
using System.Data.SqlClient;
using Microsoft.Win32;
using System.Threading;

namespace eOfficeTrayApp
{
    public partial class Form1 : Form
    {
        Thread _shedulerThread;
        string _strConnection;
        eOfficeDevManager.eOfficeDevManager _devMan = new eOfficeDevManager.eOfficeDevManager();
        //mail
        MailLogFile _logFile = new MailLogFile();

        //SheduledReportForwarder _reportScheduler = new SheduledReportForwarder();

        ReportGen _reportGen = new ReportGen();

        public string StrConnection
        {
            get { return _strConnection; }
            set { _strConnection = value; }
        }
        public Form1()
        {
            _logFile.MailWriter("Application start");
            InitializeComponent();
            this.ShowInTaskbar = false;
            this.WindowState = FormWindowState.Minimized;
            FillConnectionStr();
                
            //BMJO create a new thread here
            //_shedulerThread = new Thread(ShedulerThread);
            //_shedulerThread.Start();
        }

        private void ShedulerThread()
        {
            //mail
            //_logFile.MailWriter("Thread started..");

            //Create and instance of sheduler class 
           
            //_reportScheduler.ConnectionString = _strConnection;
            
            //while (true)
            //{
            //    //mail
            //    _logFile.MailWriter("Main function running...");
            //    //Call the main functiion of sheduler 
            //    if (_reportScheduler.Run())
            //    {                   
            //        return;
            //    }
            //}
        }


        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            _devMan.StopService();
            this.Close();            
        }
        //public void LogWrite(string Log)
        //{
        //    string strFileName = "LogFile.txt";
        //    StreamWriter sWriter = new StreamWriter(strFileName, true);
        //    DateTime dateTime = DateTime.Now;
        //    sWriter.WriteLine(dateTime + "\r\t" + Log + "\r\n");
        //    sWriter.Close();
        //    sWriter.Dispose();
        //}
        private void startServiceToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (_devMan.StartService())
            {
                MessageBox.Show("Service Started ! ");
                stopServiceToolStripMenuItem.Enabled = true;
                timer1.Start();
            }
            else
            {
                MessageBox.Show("Service failed");
            }
        }

        private void stopServiceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            if (_devMan.StopService())
                MessageBox.Show("Service Stopped");
            stopServiceToolStripMenuItem.Enabled = false;
           // _shedulerThread.Abort();
        }

        private void FillConnectionStr()
        {
            //XmlDocument settingsFile = new XmlDocument();
            //settingsFile.Load("config.xml");
            //XmlNode rootNode = settingsFile.DocumentElement;
            //XmlNodeList connectionList = rootNode.SelectNodes("/eOffice/ConnectionInfo");
            //for (int i = 0; i < connectionList.Count; ++i)
            //{
            //    XmlNode constr = connectionList[i].SelectSingleNode("descendant::settings");
            //    _strConnection = constr.InnerText;
            //}

            try
            {

                //Connection string stored in REgistry
                RegistryKey regKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\eBird\\eOffice1.0");
                if (regKey != null)
                {
                    _strConnection = regKey.GetValue("ConctString").ToString();
                }
                _logFile.MailWriter("Connectionstring: " + _strConnection);
            }
            catch (Exception ex)
            {
                _logFile.MailWriter("Connection failed " + ex.Message);
            }
        }

        private void LogProcessed()
        {
            try
            {
                notifyIcon1.Icon = new Icon("warn12.ico");
                startServiceToolStripMenuItem.Enabled = false;
                SqlConnection sqlcon = new SqlConnection(_strConnection);
                SqlCommand sqlcmd = new SqlCommand();
                sqlcmd.Connection = sqlcon;
                sqlcmd.CommandType = CommandType.StoredProcedure;
                sqlcmd.CommandText = "ProcessLogs";
                sqlcmd.CommandTimeout = 500;
                sqlcon.Open();
                sqlcmd.ExecuteNonQuery();
                sqlcon.Close();
                _devMan.LogWrite("Report generated successfully");
                startServiceToolStripMenuItem.Enabled = true;
                notifyIcon1.Icon = new Icon("logo.ico");
                
                
            }
            catch (Exception ex)
            {
                _devMan.LogWrite("Report generation failed : "+ex.Message);
                startServiceToolStripMenuItem.Enabled = true;
            }
        }
       

        private void Form1_Load(object sender, EventArgs e)
        {
            //eOfficeDevManager.eOfficeDevManager devMan = new eOfficeDevManager.eOfficeDevManager();
            //devMan.StartService();
            _devMan.DownloadStatusEvent += new EventHandler(_devMan_DownloadStatusEvent);
            button1.Enabled = false;
        }

        protected delegate void UpdateDelegate(object source, EventArgs e);
        void _devMan_DownloadStatusEvent(object sender, EventArgs e)
        {
            try
            {

                if (this.InvokeRequired)
                {
                    this.BeginInvoke(new UpdateDelegate(_devMan_DownloadStatusEvent), new object[] { sender, e });
                    return;
                }
                DownloadEventArg eventArg = (DownloadEventArg)e;
                textStatus.Text = eventArg.DownloadStatus.ToString();
                switch (eventArg.DownloadStatus)
                {
                    case DownloadStatus.DeviceStarted:
                        textStatus.Text = DownloadStatus.DeviceStarted.ToString();
                        textDescription.Text = eventArg.Message;
                        break;
                    case DownloadStatus.Downloaded:
                        textStatus.Text = DownloadStatus.Downloaded.ToString();
                        textDescription.Text = eventArg.Message;
                        break;
                    case DownloadStatus.Failed:
                        textStatus.Text = DownloadStatus.Failed.ToString();
                        textDescription.Text = eventArg.Message;
                        break;
                    case DownloadStatus.Fetching:
                        textStatus.Text = DownloadStatus.Fetching.ToString();
                        textDescription.Text = eventArg.Message;
                        break;
                    case DownloadStatus.NoRecords:
                        textStatus.Text = DownloadStatus.NoRecords.ToString();
                        textDescription.Text = eventArg.Message;
                        break;
                }
            }
            catch (Exception ex)
            {
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            _devMan.DownloadStatusEvent += new EventHandler(_devMan_DownloadStatusEvent);
            button1.Enabled = false;
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.Visible = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.Visible = false;
        }
        

        private void timer1_Tick(object sender, EventArgs e)
        {
            LogProcessed();
        }



        //protected delegate void UpdateDelegate(object source, EventArgs e);


        //void pupSearch_UpdateLibrarySearchStatus(object sender, EventArgs e)
        //{

        //    if (this.InvokeRequired)
        //    {
        //        this.BeginInvoke(new UpdateDelegate(pupSearch_UpdateLibrarySearchStatus), new object[] { sender, e });
        //        return;
        //    }

        //    //functions code will go here

           

        //}
    }
}
